package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.mapper.HotUpdateConfigMapper;
import com.itjin.model.domain.entity.HotUpdateConfig;
import com.itjin.model.domain.vo.HotUpdateConfigVO;
import com.itjin.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ConfigServiceImpl extends ServiceImpl<HotUpdateConfigMapper, HotUpdateConfig> implements ConfigService {

  @Value("${file.upload.path:/tmp/uploads}")
  private String uploadPath;

  @Value("${file.download.baseUrl:http://localhost:8080/download}")
  private String downloadBaseUrl;

  @Override
  public List<HotUpdateConfigVO> getLatestConfigs(String currentVersion, String platform) {
    try {
      // 1. 参数校验
      if (currentVersion == null || currentVersion.isEmpty()) {
        throw new IllegalArgumentException("当前版本不能为空");
      }
      if (platform == null || platform.isEmpty()) {
        throw new IllegalArgumentException("平台不能为空");
      }

      // 2. 查询该平台下比当前版本更新的配置
      QueryWrapper<HotUpdateConfig> wrapper = new QueryWrapper<>();
      wrapper.eq("platform", platform.toLowerCase())
          .eq("status", 1)
          .gt("version", currentVersion)
          .orderByDesc("version");

      List<HotUpdateConfig> configs = this.list(wrapper);

      // 3. 转换为VO
      return configs.stream()
          .map(config -> HotUpdateConfigVO.builder()
              .version(config.getVersion())
              .platform(config.getPlatform())
              .downloadUrl(config.getDownloadUrl())
              .description(config.getDescription())
              .forceUpdate(config.getForceUpdate() == 1)
              .releaseTime(config.getReleaseTime())
              .build())
          .collect(Collectors.toList());
    } catch (Exception e) {
      log.error("获取最新配置失败", e);
      return new ArrayList<>();
    }
  }

  @Override
  public boolean addConfig(HotUpdateConfig config) {
    try {
      // 1. 参数校验
      if (config == null) {
        throw new IllegalArgumentException("配置信息不能为空");
      }
      if (config.getVersion() == null || config.getVersion().isEmpty()) {
        throw new IllegalArgumentException("版本号不能为空");
      }
      if (config.getPlatform() == null || config.getPlatform().isEmpty()) {
        throw new IllegalArgumentException("平台不能为空");
      }

      // 2. 检查是否已存在相同版本和平台的配置
      QueryWrapper<HotUpdateConfig> wrapper = new QueryWrapper<>();
      wrapper.eq("version", config.getVersion())
          .eq("platform", config.getPlatform().toLowerCase());

      if (this.count(wrapper) > 0) {
        throw new IllegalArgumentException("该版本的配置已存在");
      }

      // 3. 保存配置
      config.setPlatform(config.getPlatform().toLowerCase());
      config.setStatus(1);
      return this.save(config);
    } catch (Exception e) {
      log.error("添加配置失败", e);
      throw new RuntimeException("添加配置失败: " + e.getMessage());
    }
  }

  @Override
  public boolean updateConfig(HotUpdateConfig config) {
    try {
      // 1. 参数校验
      if (config == null || config.getId() == null) {
        throw new IllegalArgumentException("配置信息不完整");
      }

      // 2. 更新配置
      if (config.getPlatform() != null) {
        config.setPlatform(config.getPlatform().toLowerCase());
      }

      return this.updateById(config);
    } catch (Exception e) {
      log.error("更新配置失败", e);
      throw new RuntimeException("更新配置失败: " + e.getMessage());
    }
  }

  @Override
  public boolean deleteConfig(Integer id) {
    try {
      // 1. 参数校验
      if (id == null || id <= 0) {
        throw new IllegalArgumentException("配置ID不合法");
      }

      // 2. 删除配置（逻辑删除）
      HotUpdateConfig config = new HotUpdateConfig();
      config.setId(id);
      config.setStatus(0);

      return this.updateById(config);
    } catch (Exception e) {
      log.error("删除配置失败", e);
      throw new RuntimeException("删除配置失败: " + e.getMessage());
    }
  }

  @Override
  public String uploadApkAndGenerateConfig(MultipartFile file, String version, String platform, String description,
      Integer forceUpdate) {
    try {
      // 1. 参数校验
      if (file == null || file.isEmpty()) {
        throw new IllegalArgumentException("上传文件不能为空");
      }
      if (version == null || version.isEmpty()) {
        throw new IllegalArgumentException("版本号不能为空");
      }
      if (platform == null || platform.isEmpty()) {
        throw new IllegalArgumentException("平台不能为空");
      }

      // 标准化平台名称
      platform = platform.toLowerCase();
      if (!platform.equals("android") && !platform.equals("ios")) {
        throw new IllegalArgumentException("平台只能是android或ios");
      }

      // 2. 检查版本是否已存在
      QueryWrapper<HotUpdateConfig> wrapper = new QueryWrapper<>();
      wrapper.eq("version", version)
          .eq("platform", platform)
          .eq("status", 1);

      if (this.count(wrapper) > 0) {
        throw new IllegalArgumentException("该版本的配置已存在");
      }

      // 3. 创建上传目录
      String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
      String uploadDir = uploadPath + "/" + platform + "/" + dateDir;
      File dir = new File(uploadDir);
      if (!dir.exists()) {
        boolean mkdirs = dir.mkdirs();
        if (!mkdirs) {
          throw new RuntimeException("创建上传目录失败");
        }
      }

      // 4. 生成文件名并保存文件
      String originalFilename = file.getOriginalFilename();
      String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf("."))
          : ".apk";
      String fileName = version + "_" + System.currentTimeMillis() + extension;
      String filePath = uploadDir + "/" + fileName;

      File dest = new File(filePath);
      file.transferTo(dest);

      // 5. 生成下载链接
      String downloadUrl = downloadBaseUrl + "/" + platform + "/" + dateDir + "/" + fileName;

      // 6. 创建配置记录
      HotUpdateConfig config = new HotUpdateConfig();
      config.setVersion(version);
      config.setPlatform(platform);
      config.setDownloadUrl(downloadUrl);
      config.setDescription(description);
      config.setForceUpdate(forceUpdate);
      config.setReleaseTime(new Date());
      config.setStatus(1);

      // 7. 保存配置
      boolean success = this.save(config);
      if (!success) {
        // 如果保存失败，删除上传的文件
        dest.delete();
        throw new RuntimeException("保存配置失败");
      }

      return downloadUrl;
    } catch (IOException e) {
      log.error("文件上传失败", e);
      throw new RuntimeException("文件上传失败: " + e.getMessage());
    }
  }
}